import React from 'react';
import {toJS} from 'mobx';
import {Provider} from 'mobx-react';
import Store from './store';
import getRouter from './router';
import {Tool, ToolRoute} from './utils';

import './App.scss';

/**
 * 顶层组件
 */
export default class App extends React.Component {
  constructor(props) {
    super(props);

    let isInit = window._ENV_.mode === 'beta' || window._ENV_.mode === 'prod';
    this.store = new Store(isInit); //如果不需要初始化状态，则参数传fasle
  }

  componentDidMount() {
    //在页面刷新时将mobx里的信息保存到sessionStorage里
    window.addEventListener('beforeunload', () => this.store.saveState());

    //检查路由访问权限
    // this.checkRoute();
    //监听路由改变
    window.onhashchange = (e) => {
      //切换路由后，需要将滚动条的位置恢复到初始值
      let d = document.getElementsByClassName('ant-layout-content')[0];
      if (d) d.scrollTop = 0;

      // this.checkRoute();
    };

    if (window._ENV_.mode === 'dev' || window._ENV_.mode === 'beta') {
      this.registerVconsole()
    }

  }

  componentWillUnmount() {
    //页面销毁时，取消路由监听
    window.onhashchange = (e) => null;
  }

  render() {
    return <Provider store={this.store}>{getRouter()}</Provider>;
  }

  /**
   * 检查路由访问权限
   */
  checkRoute() {
    // if (!ToolRoute.checkLogin()) return;

    let routerFormat = this.store.routerFormat; //格式化的路由列表
    //如果routerFormat为空，就重新获取
    if (!routerFormat || !routerFormat.menu) {
      let router = ToolRoute.formatRouter(Tool.getUser().auth, 1); //根据角色类型获取左侧菜单列表和格式化路由列表
      routerFormat = router.routerFormat;
      this.store.setRouterMenu(router.routerMenu); //在根Store中保存左侧菜单
      this.store.setRouterFormat(router.routerFormat);
    } else {
      routerFormat = toJS(routerFormat);
    }

    let result = ToolRoute.checkRoute(routerFormat);
    this.store.setRouterData(result);
  }
  /**
   * vConsole 调试工具
   */
  registerVconsole() {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://cdn.basestonedata.com/jlib/vconsole.last.min.js'
    document.getElementsByTagName('body')[0].appendChild(script)
    script.onload = () => {
      new VConsole() // eslint-disable-line
    }
  }
}
